﻿using Newtonsoft.Json;
using System.Runtime.CompilerServices;

namespace HsServerHa
{
    public static class DataFormat
    {
        public static int ToInt(this object val)
        {
            if (val == null)
            {
                return 0;
            }
            else
            {
                int result;
                int.TryParse(val.ToString(), out result);
                return result;
            }
        }

        public static long TLong(this object val)
        {
            if (val == null)
            {
                return 0;
            }
            else
            {
                long result;
                long.TryParse(val.ToString(), out result);
                return result;
            }
        }

        public static bool? ToBool(this object val)
        {
            try
            {
                if (val == null)
                {
                    return null;
                }
                else
                {
                    bool result;
                    bool.TryParse(val.ToString(), out result);
                    return result;
                }
            }
            catch (System.Exception ex)
            {

                return null;
            }
          
        }

        public static T ToCopy<T>(this object val) where T : class
        {
            try
            {
                var str = JsonConvert.SerializeObject(val);
                return JsonConvert.DeserializeObject<T>(str);
            }
            catch (System.Exception ex)
            { 
                return default;
            }
        }
    }
}
